#!/usr/bin/python
# -*- coding: UTF-8 -*-
# code=utf-8
import requests
import re
import json
import os,stat
import urllib.request
import traceback
import datetime
import time
import random
from PIL import Image

# 保存图片
def save_img(img_url,file_path,file_name):
	try:
	    #是否有这个路径
	    if not os.path.exists(file_path):
		    #创建路径
		    os.makedirs(file_path)
	    #获得图片后缀
	    file_suffix = os.path.splitext(img_url)[1]
	    #拼接图片名（包含路径）
	    filename = '{}{}{}'.format(file_path,os.sep,file_name)
	    #下载图片，并保存到文件夹中
	    urllib.request.urlretrieve(img_url,filename=filename)
	    return filename
	except IOError as e:
		traceback.print_exc()
	except Exception as e:
	    print("Exception")

#获取cookies
def get_cookies():
	#打开所保存的cookies内容文件
	f=open(r'cookies.txt','r')
	#初始化cookies字典变量
	cookies={}
	#按照字符：进行划分读取
	for line in f.read().split(';'):	
		#其设置为1就会把字符串拆分成2份
		name,value=line.strip().split('=',1)
		cookies[name]=value  #为字典cookies添加内容
	return cookies

#上传图片
def upload_img(img_path):
	cookies = get_cookies()
	files = {'upfile': open(img_path, 'rb')}     
	url = "https://mp.toutiao.com/tools/upload_picture/?type=ueditor&pgc_watermark=0&action=uploadimage&encode=utf-8"
	response=requests.post(url, files=files, cookies=cookies)
	time.sleep(1)
	json = response.json()
	return json

def add_article(data):
	data = {
		"article_type":0,
		"title":data['title'],
		"content":data['content'],
		"activity_tag":0,
		"title_id": str(round(time.time() * 1000))+"_"+str(random.randint(1000000000000000, 9999999999999999)),
		"claim_origin":0,
		"article_ad_type":3,
		"add_third_title":0,
		"recommend_auto_analyse":0,
		"tag":"",
		"article_label":"",
		"is_fans_article":0,
		"quote_hot_spot":0,
		"govern_forward":0,
		"push_status":0,
		"push_android_title":"",
		"push_android_summary":"",
		"push_ios_summary":"",
		"timer_status":0,
		"timer_time":time.strftime("%Y-%m-%d %H:%M", time.localtime()) ,
		"praise":0,
		"community_sync":0,
		"checkReport":0,
		"reportBizType":"",
		"column_chosen":0,
		"pgc_id":0,
		"qy_self_recommendation":0,
		"pgc_feed_covers":[],
		"from_diagnosis":0,
		"origin_debut_check_pgc_normal":0,
		"tree_plan_article":0,
		"save":1
	}
	url = "https://mp.toutiao.com/core/article/edit_article_post/?source=mp&type=article"
	cookies = get_cookies()
	response = requests.post(url, data=data, cookies=cookies)
	return response

#获取原文链接
def get_url():
	#打开所保存的cookies内容文件
	f=open(r'url.txt','r')
	return f.read()


# 主程序运行
if __name__ == "__main__":
	# 快看漫画
	url = get_url()
	headers = {
		'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
	}
	# 发起Get请求
	response = requests.get(url, headers=headers)
	the_html = response.text
	# 获取漫画图片
	html = the_html.replace('\\u002F', '/')
	pat = re.compile('{width:b,height:c,url:"(.*?)"},', re.S)
	results = re.findall(pat, html)
	# 获取标题
	title_pat = re.compile('<span class="works">作品：</span> <a href="/">查看首页</a>.*?-\n.*?<a .*?>(.*?)</a>.*?-(.*?)</h3>.*?<div class="tab cls">', re.S)
	titles = re.findall(title_pat, the_html)
	titles = titles[0]
	title = "《"+titles[0].strip()+"》" +"："+ titles[1].strip()

	# 图片下标
	img_i = 0
	# 推文内容(图片组成)
	content = '<p><br></p><div class="pgc-img">'
	if results:
		for result in results:
			# 下载图片到本地
			file_path = os.getcwd()+"/img"
			file_name = str(img_i)+".png"
			img_i = img_i +1
			img_path = save_img(result,file_path,file_name)

			# 获取图片大小
			im = Image.open(img_path)#返回一个Image对象
			width = str(im.size[0])
			height = str(im.size[1])

			#上传图片
			img_data = upload_img(img_path)
			content += '<img class="" src="'+img_data['url']+'" data-ic="false" data-ic-uri="" data-height="'+height+'" data-width="'+width+'" data-story_id="0" data-image_ids="[]" image_type="1" mime_type="image/jpeg" web_uri="'+img_data['original']+'" img_width="'+width+'" img_height="'+height+'">';
	
	#发布今日头条推送
	content += '<p class="pgc-img-caption"></p></div><p><br></p>'	
	art_data = {"title":title,"content":content}
	response = add_article(art_data)
	print(response)



